package com.hejjon;

/**
 * 4. 寻找两个正序数组的中位数
 * Created by caoshi at 21:00 2021-10-16
 */
public class FindMedian {


    public static void main(String[] args) {
        int[] a1 = new int[]{3, 2, 1, 5, 6, 7};
        int[] a2 = new int[]{7, 4, 2};

        FindMedian fm = new FindMedian();
        double midNumber = fm.findMedianSortedArrays(a1, a2);
        System.out.println(midNumber);

    }


    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int[] result = mergeArray(nums1, nums2);
//        System.out.println(Arrays.toString(result));
        int length = result.length;
        double midNum = 0;

        if ((length & 1) != 0) {
            midNum = result[(length - 1) / 2];
        } else {
            int leftIndex = length / 2 - 1;
            int rightIndex = length / 2;
            midNum = (result[leftIndex] + result[rightIndex]) / 2.0;
        }
        return midNum;
    }

    private int[] mergeArray(int[] arr1, int[] arr2) {
        int len1 = arr1.length;
        int len2 = arr2.length;
        int[] result = new int[len1 + len2];

        System.arraycopy(arr1, 0, result, 0, len1);
        System.arraycopy(arr2, 0, result, len1, len2);

        for (int i = 0; i < result.length; i++) {
            for (int j = 0; j < result.length - i - 1; j++) {
                if (result[j] > result[j + 1]) {
                    int temp = result[j];
                    result[j] = result[j + 1];
                    result[j + 1] = temp;
                }
            }
        }
        return result;
    }


}
